package com.hao_family.atcrowdfunding.controller.permission;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hao_family.atcrowdfunding.beans.TAdmin;
import com.hao_family.atcrowdfunding.service.AdminService;

@Controller
public class AdminController {
	@Autowired
	AdminService adminService;
	/**
	 * 5.接受edit页面请求
	 * @return
	 */
	@GetMapping("/admin/edit.html")
	public String goToEditPage(@RequestParam("id")Integer id,Model model) {
		TAdmin admin = adminService.getAdminById(id);
		model.addAttribute("editer", admin);
		return "permission/admin_edit";
	}
	
	/**
	 * 保存修改后数据
	 * @param admin
	 * @return
	 */
	@PostMapping("/admin/update.html")
	public String doUpdate(TAdmin admin,HttpSession session,Model model) {
		adminService.updateAdmin(admin);
		Integer pn = (Integer) session.getAttribute("pn");
		String condition = (String) session.getAttribute("condition");
		model.addAttribute("pn", pn);
		model.addAttribute("condition", condition);
		return "redirect:/admin/index.html";
	}
	
	/**
	 * 处理添加请求
	 * @return
	 */
	@GetMapping("/admin/add.html")
	public String goToAddPage() {
		return "permission/admin_add";
	}
	
	@PostMapping("/admin/save.html")
	public String doSave(TAdmin admin ,Model model) {
		String msg = adminService.saveAdmin(admin);
		if (msg==null) {
			return "redirect:/admin/index.html?pn="+ Integer.MAX_VALUE;
		}else {
			model.addAttribute("erroradmin", admin);
			model.addAttribute("msg", msg);
			return "permission/admin_add";
		}
	}
	@GetMapping("/admin/delete.html")
	public String doDelete(@RequestParam("id")Integer id,Model model,HttpSession session) {
		adminService.deleteAdminById(id);
		Integer pn = (Integer) session.getAttribute("pn");
		String condition = (String) session.getAttribute("condition");
		model.addAttribute("pn", pn);
		model.addAttribute("condition", condition);
		return "redirect:/admin/index.html";
	}
	/**
	 * 批量删
	 * @param ids
	 * @param model
	 * @param session
	 */
	@GetMapping("/admin/batch/delete")
	public String doBatchDelete(@RequestParam("ids")String ids,Model model,HttpSession session) {
		Integer pn = (Integer) session.getAttribute("pn");
		String condition = (String) session.getAttribute("condition");
		model.addAttribute("pn", pn);
		model.addAttribute("condition", condition);
		if (!StringUtils.isEmpty(ids)) {
			String[] idList = ids.split(",");
			for (String string : idList) {
				Integer id = Integer.parseInt(string);
				adminService.deleteAdminById(id);
			}
		}
		return "redirect:/admin/index.html";
	}
}
